{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Objectives\n",
    "\n",
    "## Overview\n",
    "\n",
    "One of the key choices to make when training an ML model is what metric to choose by which to measure the efficacy of the model at learning the signal. Such metrics are useful for comparing how well the trained models generalize to new similar data.\n",
    "\n",
    "This choice of metric is a key component of AutoML because it defines the cost function the AutoML search will seek to optimize. In EvalML, these metrics are called **objectives**. AutoML will seek to minimize (or maximize) the objective score as it explores more pipelines and parameters and will use the feedback from scoring pipelines to tune the available hyperparameters and continue the search. Therefore, it is critical to have an objective function that represents how the model will be applied in the intended domain of use.\n",
    "\n",
    "EvalML supports a variety of objectives from traditional supervised ML including [mean squared error](https://en.wikipedia.org/wiki/Mean_squared_error) for regression problems and [cross entropy](https://en.wikipedia.org/wiki/Cross_entropy) or [area under the ROC curve](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) for classification problems. EvalML also allows the user to define a custom objective using their domain expertise, so that AutoML can search for models which provide the most value for the user's problem."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optimization vs Ranking Objectives"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are many common objectives used for evaluating model performance. However, not all of these objectives should be used to optimize AutoMLSearch. Consider the popular objective `recall`, which is the number of true positives divided by the number of true positives and false negatives. If the model has no false negatives, the `recall` ends up being a perfect score of 1. During automatic optimization, models can exploit this by predicting the positive label in every case, making a completely useless but seemingly highly performant model. However, this objective is still useful when trying to evaluate performance after a model has been trained.\n",
    "\n",
    "Due to this potential issue, we define two types of objectives: optimization and ranking. Optimization objectives are those that can be used within AutoMLSearch to train performant models. Ranking objectives can be used after AutoMLSearch has been run, to rank or otherwise evaluate model performance. These include all of the optimization metrics, as well as all other important metrics such as recall that are excluded from optimization.\n",
    "\n",
    "Note that we also define a third class of objectives, non-core objectives, which are domain-specific and require additional configuration before they can be used."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimization Objectives\n",
    "\n",
    "Use the `get_optimization_objectives` method to get a list of which objectives can be used for optimization in AutoMLSearch for each problem type:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from evalml.objectives import get_optimization_objectives\n",
    "from evalml.problem_types import ProblemTypes\n",
    "\n",
    "for objective in get_optimization_objectives(ProblemTypes.BINARY):\n",
    "    print(objective.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ranking Objectives\n",
    "\n",
    "Use the `get_ranking_objectives` method to get a list of which objectives are included with EvalML for each problem type:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from evalml.objectives import get_ranking_objectives\n",
    "\n",
    "for objective in get_ranking_objectives(ProblemTypes.BINARY):\n",
    "    print(objective.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "EvalML defines a base objective class for each problem type: `RegressionObjective`, `BinaryClassificationObjective` and `MulticlassClassificationObjective`. All EvalML objectives are a subclass of one of these."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Binary Classification Objectives and Thresholds"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All binary classification objectives have a `threshold` property. Some binary classification objectives like log loss and AUC are unaffected by the choice of binary classification threshold, because they score based on predicted probabilities or examine a range of threshold values. These metrics are defined with `score_needs_proba` set to False. For all other binary classification objectives, we can compute the optimal binary classification threshold from the predicted probabilities and the target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from evalml.pipelines import BinaryClassificationPipeline\n",
    "from evalml.demos import load_fraud\n",
    "from evalml.objectives import F1\n",
    "\n",
    "X, y = load_fraud(n_rows=100)\n",
    "X.ww.init(\n",
    "    logical_types={\n",
    "        \"provider\": \"Categorical\",\n",
    "        \"region\": \"Categorical\",\n",
    "        \"currency\": \"Categorical\",\n",
    "        \"expiration_date\": \"Categorical\",\n",
    "    }\n",
    ")\n",
    "objective = F1()\n",
    "pipeline = BinaryClassificationPipeline(\n",
    "    component_graph=[\n",
    "        \"Imputer\",\n",
    "        \"DateTime Featurizer\",\n",
    "        \"One Hot Encoder\",\n",
    "        \"Random Forest Classifier\",\n",
    "    ]\n",
    ")\n",
    "pipeline.fit(X, y)\n",
    "print(pipeline.threshold)\n",
    "print(pipeline.score(X, y, objectives=[objective]))\n",
    "\n",
    "y_pred_proba = pipeline.predict_proba(X)[True]\n",
    "pipeline.threshold = objective.optimize_threshold(y_pred_proba, y)\n",
    "print(pipeline.threshold)\n",
    "print(pipeline.score(X, y, objectives=[objective]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Custom Objectives\n",
    "\n",
    "Often times, the objective function is very specific to the use-case or business problem. To get the right objective to optimize requires thinking through the decisions or actions that will be taken using the model and assigning a cost/benefit to doing that correctly or incorrectly based on known outcomes in the training data.\n",
    "\n",
    "Once you have determined the objective for your business, you can provide that to EvalML to optimize by defining a custom objective function.\n",
    "\n",
    "### Defining a Custom Objective Function\n",
    "\n",
    "To create a custom objective class, we must define several elements:\n",
    "\n",
    "* `name`: The printable name of this objective.\n",
    "\n",
    "* `objective_function`: This function takes the predictions, true labels, and an optional reference to the inputs, and returns a score of how well the model performed.\n",
    "\n",
    "* `greater_is_better`: `True` if a higher `objective_function` value represents a better solution, and otherwise `False`.\n",
    "\n",
    "* `score_needs_proba`: Only for classification objectives. `True` if the objective is intended to function with predicted probabilities as opposed to predicted values (example: cross entropy for classifiers).\n",
    "\n",
    "* `decision_function`: Only for binary classification objectives. This function takes predicted probabilities that were output from the model and a binary classification threshold, and returns predicted values.\n",
    "\n",
    "* `perfect_score`: The score achieved by a perfect model on this objective.\n",
    "\n",
    "* `expected_range`: The expected range of values we want this objective to output, which doesn't necessarily have to be equal to the possible range of values. For example, our expected R2 range is from `[-1, 1]`, although the actual range is `(-inf, 1]`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Fraud Detection\n",
    "\n",
    "To give a concrete example, let's look at how the [fraud detection](../demos/fraud.ipynb) objective function is built."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from evalml.objectives.binary_classification_objective import (\n",
    "    BinaryClassificationObjective,\n",
    ")\n",
    "import pandas as pd\n",
    "\n",
    "\n",
    "class FraudCost(BinaryClassificationObjective):\n",
    "    \"\"\"Score the percentage of money lost of the total transaction amount process due to fraud\"\"\"\n",
    "\n",
    "    name = \"Fraud Cost\"\n",
    "    greater_is_better = False\n",
    "    score_needs_proba = False\n",
    "    perfect_score = 0.0\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        retry_percentage=0.5,\n",
    "        interchange_fee=0.02,\n",
    "        fraud_payout_percentage=1.0,\n",
    "        amount_col=\"amount\",\n",
    "    ):\n",
    "        \"\"\"Create instance of FraudCost\n",
    "\n",
    "        Args:\n",
    "            retry_percentage (float): What percentage of customers that will retry a transaction if it\n",
    "                is declined. Between 0 and 1. Defaults to .5\n",
    "\n",
    "            interchange_fee (float): How much of each successful transaction you can collect.\n",
    "                Between 0 and 1. Defaults to .02\n",
    "\n",
    "            fraud_payout_percentage (float): Percentage of fraud you will not be able to collect.\n",
    "                Between 0 and 1. Defaults to 1.0\n",
    "\n",
    "            amount_col (str): Name of column in data that contains the amount. Defaults to \"amount\"\n",
    "        \"\"\"\n",
    "        self.retry_percentage = retry_percentage\n",
    "        self.interchange_fee = interchange_fee\n",
    "        self.fraud_payout_percentage = fraud_payout_percentage\n",
    "        self.amount_col = amount_col\n",
    "\n",
    "    def decision_function(self, ypred_proba, threshold=0.0, X=None):\n",
    "        \"\"\"Determine if a transaction is fraud given predicted probabilities, threshold, and dataframe with transaction amount\n",
    "\n",
    "        Args:\n",
    "            ypred_proba (pd.Series): Predicted probablities\n",
    "            X (pd.DataFrame): Dataframe containing transaction amount\n",
    "            threshold (float): Dollar threshold to determine if transaction is fraud\n",
    "\n",
    "        Returns:\n",
    "            pd.Series: Series of predicted fraud labels using X and threshold\n",
    "        \"\"\"\n",
    "        if not isinstance(X, pd.DataFrame):\n",
    "            X = pd.DataFrame(X)\n",
    "\n",
    "        if not isinstance(ypred_proba, pd.Series):\n",
    "            ypred_proba = pd.Series(ypred_proba)\n",
    "\n",
    "        transformed_probs = ypred_proba.values * X[self.amount_col]\n",
    "        return transformed_probs > threshold\n",
    "\n",
    "    def objective_function(self, y_true, y_predicted, X):\n",
    "        \"\"\"Calculate amount lost to fraud per transaction given predictions, true values, and dataframe with transaction amount\n",
    "\n",
    "        Args:\n",
    "            y_predicted (pd.Series): predicted fraud labels\n",
    "            y_true (pd.Series): true fraud labels\n",
    "            X (pd.DataFrame): dataframe with transaction amounts\n",
    "\n",
    "        Returns:\n",
    "            float: amount lost to fraud per transaction\n",
    "        \"\"\"\n",
    "        if not isinstance(X, pd.DataFrame):\n",
    "            X = pd.DataFrame(X)\n",
    "\n",
    "        if not isinstance(y_predicted, pd.Series):\n",
    "            y_predicted = pd.Series(y_predicted)\n",
    "\n",
    "        if not isinstance(y_true, pd.Series):\n",
    "            y_true = pd.Series(y_true)\n",
    "\n",
    "        # extract transaction using the amount columns in users data\n",
    "        try:\n",
    "            transaction_amount = X[self.amount_col]\n",
    "        except KeyError:\n",
    "            raise ValueError(\"`{}` is not a valid column in X.\".format(self.amount_col))\n",
    "\n",
    "        # amount paid if transaction is fraud\n",
    "        fraud_cost = transaction_amount * self.fraud_payout_percentage\n",
    "\n",
    "        # money made from interchange fees on transaction\n",
    "        interchange_cost = (\n",
    "            transaction_amount * (1 - self.retry_percentage) * self.interchange_fee\n",
    "        )\n",
    "\n",
    "        # calculate cost of missing fraudulent transactions\n",
    "        false_negatives = (y_true & ~y_predicted) * fraud_cost\n",
    "\n",
    "        # calculate money lost from fees\n",
    "        false_positives = (~y_true & y_predicted) * interchange_cost\n",
    "\n",
    "        loss = false_negatives.sum() + false_positives.sum()\n",
    "\n",
    "        loss_per_total_processed = loss / transaction_amount.sum()\n",
    "\n",
    "        return loss_per_total_processed"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
